package com.exam.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.exam.util.ReadExcel;


/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

	// 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 上传后的文件存哪？？  excel  ,jpg
		// 1 本项目下 upload 下,好处是 html 可直接访问 ，坏处是资源紧张
		// 2 放到别的服务器去 ， 好处是不占用本项目资源  http://项目/文件夹/temo.jpg
		
		//找项目的发布位置
		///Users/sanzang/Documents/WebApps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/HelloJavaWeb/upload		
		
		
        DiskFileItemFactory factory = new DiskFileItemFactory();  // 配置上传参数
        factory.setSizeThreshold(MEMORY_THRESHOLD);       // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // 设置临时存储目录
 
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);// 设置最大文件上传值
        upload.setSizeMax(MAX_REQUEST_SIZE);// 设置最大请求值 (包含文件和表单数据)
        upload.setHeaderEncoding("UTF-8"); // 中文处理
        
		String path = request.getServletContext().getRealPath("/upload");  //文件实际存放位置
		// 如何提取表单数据
		File storeFile =null;
		try {
			List<FileItem> formItems = upload.parseRequest(request);
			 if (formItems != null && formItems.size() > 0) {
				 for (FileItem item : formItems) {  // username,pass,file
					if( !item.isFormField()) {
						String filename = item.getName(); // 文件名
						String filepath = path + File.separator + filename;
						System.out.println("在上传文件"+ filepath);
						storeFile = new File(filepath);
						item.write(storeFile);
					}
				}
				 // 上传成功后 ，读取excel 文件，放入数据库
				 ReadExcel.importExcel(storeFile);
				 response.sendRedirect("/OnlineExam1/admin/student_manage.jsp");
			 }
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
	}

	 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
